package com.sakura.demo2.auth.controller;

import com.sakura.demo.common.constant.AuthConstant;
import com.sakura.demo.common.model.JsonResponseEntity;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: zhengcan
 * @Date: 2022/5/17
 * @Description:
 * @Version: 1.0.0 创建
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private TokenStore sakuraTokenStore;

    @ApiOperation("用户退出登录")
    @GetMapping("/logout")
    public JsonResponseEntity<Boolean> logout(HttpServletRequest request) {
        String bearerToken = request.getHeader(AuthConstant.TOKEN_HEADER);
        if (ObjectUtils.isEmpty(bearerToken)) {
            return JsonResponseEntity.buildBusinessError("用户未登录！");
        }
        String token = bearerToken.replace(AuthConstant.TOKEN_STANDARD_STYLE, "");
        OAuth2AccessToken oAuth2AccessToken = sakuraTokenStore.readAccessToken(token);
        if (!ObjectUtils.isEmpty(oAuth2AccessToken) && !oAuth2AccessToken.isExpired()) {
            // 移除access token值
            sakuraTokenStore.removeAccessToken(oAuth2AccessToken);
            // 获取refresh token 并移除
            OAuth2RefreshToken refreshToken = oAuth2AccessToken.getRefreshToken();
            sakuraTokenStore.removeRefreshToken(refreshToken);
            sakuraTokenStore.removeAccessTokenUsingRefreshToken(refreshToken);
            return JsonResponseEntity.buildOK(true);
        }
        return JsonResponseEntity.buildOK(false);
    }

}
